<?php
declare(strict_types=1);

namespace app\admin\model;

use \app\model\Salesman as ModelSalesman;

class Salesman extends ModelSalesman
{
    /**
     * 列表
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function dataList($params) {
        $keyword = $params['keyword'] ?? '';
        $list = self::when($keyword, function ($query) use ($keyword) {
                $query->where('id|true_name|username', 'like', '%' . $keyword . '%');
            })
            ->append(['agent_salesman_num'])
//            ->withCount(['agentSalesman' => function($query, &$alias) {
//                $query->where('is_deleted', DELETE_TYPE_NO);
//                $alias = 'agent_salesman_num';  // 字段别名
//            }])
            ->order('id desc')
            ->paginate();
        return success('操作成功', $list);
    }

    /**
     * 保存
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveData($params) {
        $id = $params['id'] ?? '';
        if ($id) {
            unset($params['id']);
            $model = self::where('id', $id)->find();
            if (!$model) {
                return fail('该业务员不存在');
            }
        } else {
            $model = new self();
        }

        if ($model->save($params) !== false) {
            return success('操作成功');
        }

        return fail('操作失败');
    }

}